using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class PlayerController : MonoBehaviour
{
    public Rigidbody2D rb;

    public Collider2D collider;

    [Header("cd Image")]
    public Image cdImage;

    public Collider2D DisCollider;
    public Animator Anim;
    public float speed , jumpForce;

    public Transform groundCheck;

    public Transform headCheck;
    public LayerMask ground;

    public AudioSource hurtAudio;

    public AudioSource collectAudio;

    public float dashTime;
    private float dashLeftTime;
    private float lastDash = -10f;

    public float dashCoolDown;

    public float dashSpeed;

    private float horizontalMove=1;

    private bool jumpPressed,crouchPressed,isGround, isJump, isDashing;

    private bool isHurt = false;

    private int Cherry;

    private bool AutoUp;

    int jumpCount=3;

    public Text CherryNumber;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    void Update(){
      if(Input.GetButtonDown("Jump") && jumpCount>0){
        jumpPressed = true;

      }

      if(Input.GetKeyDown(KeyCode.F)){
          if(Time.time >= (lastDash + dashCoolDown)){
            //可以执行dash
            ReadyToDash();
          }
      }



      if(!Physics2D.OverlapCircle(headCheck.position, 0.2f, ground)){
        if(Input.GetButton("Crouch")){
          crouchPressed = true;
        }else{
          crouchPressed = false;
        }
      }

      cdImage.fillAmount -= 1.0f/dashCoolDown * Time.deltaTime;
      
      
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        //isGround = collider.IsTouchingLayers(ground);
        isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);
        //Debug.Log(isGround);
        Dash();
        if(isDashing){
          return;
        }
        if(!isHurt){
          GroundMovement();
        }else{
          if(Mathf.Abs(rb.velocity.x)<0.1f){
            isHurt = false;
          }
        }
        Jump();
        SwitchAnim();
    }

    void GroundMovement(){
      
      horizontalMove = Input.GetAxisRaw("Horizontal");
      rb.velocity =  new Vector2(horizontalMove * speed, rb.velocity.y);

      if(horizontalMove!=0){
        transform.localScale = new Vector3(horizontalMove,1,1);
      }
    }

    void Jump(){
       if(isGround){
         jumpCount = 3;
         isJump = false;
       }

       if(jumpPressed && isGround){
         SoudManage.soudManage.JumpAudio();
         isJump = true;
         rb.velocity = new Vector2(rb.velocity.x* Time.fixedDeltaTime, jumpForce);
         jumpCount--;
         jumpPressed = false;
       }
       else if(jumpPressed && jumpCount>0 && isJump){
         SoudManage.soudManage.JumpAudio();
         rb.velocity = new Vector2(rb.velocity.x* Time.fixedDeltaTime, jumpForce);
         jumpCount--;
         jumpPressed = false;
       }
    }
    
    //切换动画
    void SwitchAnim(){
      Anim.SetFloat("runing", Mathf.Abs(rb.velocity.x));
      if(!isHurt){
        Anim.SetBool("hurt",false);
        if(isGround){
          Anim.SetBool("failing", false);
          Anim.SetBool("jumping", false);
          if(crouchPressed){
            Anim.SetBool("crouch", true);
            DisCollider.enabled = false;
          }else{
            Anim.SetBool("crouch", false);
            DisCollider.enabled = true;
          }
        }else if (!isGround && rb.velocity.y>0){
          Anim.SetBool("jumping", true);
        }else if(rb.velocity.y<0){
          Anim.SetBool("jumping", false);
          Anim.SetBool("failing", true);
        }else{
          Anim.SetBool("jumping", false);
          Anim.SetBool("failing", true);
        }
      }else{
        Anim.SetBool("hurt",true);
      }
      

    }

    //碰撞触发器
    private void OnTriggerEnter2D(Collider2D other) {
      //收集品
      if(other.tag == "Collection"){
        Destroy(other.gameObject);
        collectAudio.Play();
        Cherry += 1; 
        CherryNumber.text = Cherry.ToString();
      }

      //死亡
      if(other.tag == "DeadLine"){
        GetComponent<AudioSource>().enabled = false;
        Invoke("Restart", 2f);
        Restart();
      }
    }

    //消灭敌人
    private void OnCollisionEnter2D(Collision2D other) {
      if(other.gameObject.tag== "Enemies"){
        Enemy enemy = other.gameObject.GetComponent<Enemy>();
        if(Anim.GetBool("failing")){
          //下落跳到头上消灭
          enemy.JumpOn();
          rb.velocity = new Vector2(rb.velocity.x, jumpForce); 
        }else{
          isHurt = true;
          hurtAudio.Play();
          //受伤
          if(transform.position.x < other.gameObject.transform.position.x){
            rb.velocity =  new Vector2( -5, rb.velocity.y);
          }else{
            rb.velocity =  new Vector2( 5, rb.velocity.y);
          }
          
        }
        
      }
    }

    void Restart(){
      SceneManager.LoadScene(SceneManager.GetActiveScene().name); 
    }

    void ReadyToDash(){
      isDashing = true;
      dashLeftTime = dashTime;
      lastDash = Time.time;
      cdImage.fillAmount = 1.0f;
    }

    void Dash(){
      if(isDashing){
        if(dashLeftTime > 0){
          rb.velocity = new Vector2(dashSpeed* horizontalMove,rb.velocity.y);

          dashLeftTime -= Time.deltaTime;

          ShadowPool.instance.GetFromPool();
        }
        if(dashLeftTime<=0){
          isDashing = false;
        }
      }
      
    }


}
